<?php
namespace  zhtfrontend\components\services\classmanager;

use common\components\helpers\Fun;
use common\components\helpers\Util;
use common\models\datas\Student;
use zhtfrontend\models\datas\ArtTeaching;
use zhtfrontend\models\datas\CheckCount;
use zhtfrontend\models\datas\ClassLesson;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\ClassManageAttribute;
use zhtfrontend\models\datas\ClassManageGoods;
use zhtfrontend\models\datas\ClassManageTeacher;
use zhtfrontend\models\datas\Classroom;
use zhtfrontend\models\datas\ClassStudent;
use zhtfrontend\models\datas\GoodsAttr;
use zhtfrontend\models\datas\GoodsClassTime;
use zhtfrontend\models\datas\OrdersItems;
use zhtfrontend\models\datas\OrdersItemsRelation;
use zhtfrontend\models\datas\OrdersType;
use zhtfrontend\models\datas\StudentCheck;
use zhtfrontend\models\datas\SubstituteCheck;

class Operclassmanager
{
      public static function InsertClassStudent($model){
//            $orderType = OrdersType::find()->select('id')->where(['orders_id'=>$model->id,'type_id'=>1])->one();
            $items = OrdersItems::find()->where(['orders_id'=>$model->id])->all();
            $is_frequency = 1;
            $itemRelation = OrdersItemsRelation::find()->where(['orders_id'=>$model->id])->one();
            if($itemRelation != null){
                $is_frequency = $itemRelation->is_frequency;
            }
            $Student = Student::find()->where(['customer_id'=>$model->customer_id])->one();
            if($items != null) {
                //插入班级学生
                foreach ($items as $item){
                    $where= ['is_old'=>0,'type'=>$item->teach_type];
                    if($item->teach_type == 1){
                        $classGoods = ClassManageGoods::find()->where(['goods_id'=>$item->goods_id])->one();
                        $where['class_id']= $classGoods->class_id;
                    }else{
                        $where['associate_id']= $item->goods_id;
                    }
                   $classMangaer =  ClassManage::find()->where($where)->one();
                   $status = 0;
                   $start_time = 0;
                   $end_time = 0;
                   if($classMangaer != null){
//                       if($classMangaer->status == 1){
//                           $status = 1;
//                           $start_time = $classMangaer->start_time;
//                           $end_time = $classMangaer->start_time;
//                           if($classMangaer->type == 1){
//                               $ovo = 0;
//                               $teacher_form = GoodsAttr::find()->where(['goods_id'=>$item->goods_id,'obj_type'=>'teacher_form'])->one();
//                               if($teacher_form->value == 0){
//                                   $ovo = 1;
//                               }
//                                $AttrCount = GoodsAttr::find()->where(['goods_id'=>$item->goods_id,'obj_type'=>'class_count'])->one();
//                                $classCount = (int)$AttrCount->value; //总课次
//                                $count = ClassLesson::find()->where(['class_id'=>$classMangaer->class_id])->count();
//                                $okCount = ClassLesson::find()->where(['class_id'=>$classMangaer->class_id])->andWhere(['<','class_date',time()])->count();  //查找已经上课次数
//                                $LatelyLesson = ClassLesson::find()->where(['class_id'=>$classMangaer->class_id])->andWhere(['>','class_date',time()])->orderBy('lesson_id ASC')->one();
//                                $maxLesson = ClassLesson::find()->where(['class_id'=>$classMangaer->class_id])->orderBy('lesson_id DESC')->one();
//                                $start_time = $LatelyLesson->class_date;
//                                $s = explode(':', Util::getTime($maxLesson->end_time));
//                                $end_time = strtotime(date('Y-m-d',$maxLesson->class_date))+(int)$s[0] * 60 * 60 + (int)$s[1] * 60;
//                                $end_time = $end_time;
//
//                                //die(($count-$okCount).'ffff'.$classCount);
//                                if(($count-$okCount) < $classCount){
//                                    $timeList = GoodsClassTime::find()->where(['goods_id'=>$item->goods_id])->all();
//                                    $addLesson = $classCount - ($count-$okCount);
//                                    $i = 1;
//                                    $j = 1;
//                                    $insertLesson = [];
//                                    while ($j <= $addLesson){
//                                        $time = $maxLesson->class_date+86400*$i;
//                                        $class_today = date('w',$time);
//                                        if ($class_today == 0) {
//                                            $class_today = 7;
//                                        }
//                                        foreach ($timeList as $t){
//                                            if($t->class_day == $class_today){
//                                                $insertLesson[] = [
//                                                    'class_id'=>$maxLesson->class_id,
//                                                    'class_date'=>$time,
//                                                    'start_time'=>$maxLesson->start_time,
//                                                    'end_time'=>$maxLesson->end_time,
//                                                    'lesson'=>$maxLesson->lesson+$j,
//                                                    'title' =>$maxLesson->title,
//                                                    'status'=>0,
//                                                    'ovo'   =>$ovo,
//                                                    'lesson_type'   =>$model->order_type,
//                                                ];
//                                                $j++;
//                                            }
//                                        }
//                                        if($j == $addLesson){
//                                            $s = explode(':', Util::getTime($maxLesson->end_time));
//                                            $end_time = strtotime(date('Y-m-d',$time))+(int)$s[0] * 60 * 60 + (int)$s[1] * 60;
//                                        }
//                                        $i++;
//                                    }
//                                    Fun::getSiteDb()->createCommand()->batchInsert('{{%class_lesson}}', ['class_id','class_date','start_time', 'end_time','lesson','title','status','ovo','lesson_type'], $insertLesson)->execute();
//                                }
//                           }
//                       }
                       //把此班级中的记录改为续课
                       $classStuent = ClassStudent::find()->where(['student_id'=>$Student->id,'class_manage_id'=>$classMangaer->class_id,'status'=>1])->all();
                       if($classStuent !=null){
                           foreach ($classStuent as $items){
                               $items->status = 5;
                               $items->end_time = time();
                               $items->save(false);
                           }
                       }
                       //插入新的到班级
                       $classStudentModel = new ClassStudent();
                       $classStudentModel->class_manage_id = $classMangaer->class_id;
                       $classStudentModel->order_sales_id = $item->id;
                       $classStudentModel->student_id = $Student->id;
                       $classStudentModel->status = 0;
                       $classStudentModel->start_time = 0;
                       $classStudentModel->end_time = 0;
                       $classStudentModel->is_deposit = 1;
                       $classStudentModel->mode = '2';
                       $classStudentModel->is_paydeposit = 1;
                       $classStudentModel->is_frequency = $is_frequency;
                       $classStudentModel->save(false);
                   }
                }
            }
      }

      //转化或续费插入课次与打卡记录
      public static function addclasslesson($model){
          $items = OrdersItems::find()->where(['orders_id'=>$model->id])->all();
          foreach ($items as $item){
              $modelRelaction = OrdersItemsRelation::find()->where(['orders_items_id'=>$item->id])->one();
              if($item->teach_type == 1){//技教学转化/续费
                  $ovo = 0;
                  $teacher_form = GoodsAttr::find()->where(['goods_id'=>$item->goods_id,'obj_type'=>'teacher_form'])->one();
                  if($teacher_form->value == 0){
                      $ovo = 1;
                  }
                 $timeList = GoodsClassTime::find()->where(['goods_id'=>$item->goods_id])->all();
                 $classmanage = ClassManage::find()->where(['associate_id'=>$item->goods_id,'type'=>1,'is_old'=>0])->one();
                 $lessonCount = ClassLesson::find()->where(['class_id'=>$classmanage->class_id])->count();
                 $classstudent = ClassStudent::find()->where(['class_manage_id'=>$classmanage->class_id,'student_id'=>$item->student_id])->one();
                 $checkCount = StudentCheck::find()->where(['class_student_id'=>$classstudent->id,'student_id'=>$item->student_id])->count();
                  $MaxCheck = StudentCheck::find()->where(['student_id'=>$item->student_id,'class_student_id'=>$classstudent->id])->orderBy('class_lesson_id DESC')->one();
                 $total = $checkCount+$modelRelaction->lesson;
                 if($lessonCount < $total){ //如果课次表课次数小于词学生转化的课次数
                     $Surplus = $total-$lessonCount;
                     $maxLesson = ClassLesson::find()->where(['class_id'=>$classmanage->class_id])->orderBy('lesson DESC')->one();
                     $i = 1;
                     $j = 0;
                     $insertLesson = [];
                     while($j < $Surplus){
                         $time = $maxLesson->class_date+86400*$i;
                         $class_today = date('w',$time);
                         if ($class_today == 0) {
                             $class_today = 7;
                         }
                         foreach ($timeList as $t){
                             if($t->class_day == $class_today){
                                 $insertLesson[] = [
                                     'class_id'=>$maxLesson->class_id,
                                     'class_date'=>$time,
                                     'start_time'=>$maxLesson->start_time,
                                     'end_time'=>$maxLesson->end_time,
                                     'lesson'=>$maxLesson->lesson+$j+1,
                                     'title' =>$maxLesson->title,
                                     'status'=>0,
                                     'ovo'   =>$ovo,
                                     'lesson_type'   =>$model->order_type,
                                 ];
                                 $j++;
                             }
                         }
                         $i++;
                     }
//                     print_r($insertLesson);
                     Fun::getSiteDb()->createCommand()->batchInsert('{{%class_lesson}}', ['class_id','class_date','start_time', 'end_time','lesson','title','status','ovo','lesson_type'], $insertLesson)->execute();
                 }
              }else{ //艺教学转化/续费
                  $artModel = ArtTeaching::findOne($item->goods_id);
                  $classmanage = ClassManage::find()->where(['associate_id'=>$artModel->id,'type'=>2,'is_old'=>0])->one();
                  $lessonCount = ClassLesson::find()->where(['class_id'=>$classmanage->class_id])->count();
                  $classstudent = ClassStudent::find()->where(['class_manage_id'=>$classmanage->class_id,'student_id'=>$item->student_id])->one();
                  $checkCount = StudentCheck::find()->where(['class_student_id'=>$classstudent->id,'student_id'=>$item->student_id])->count();
                  $MaxCheck = StudentCheck::find()->where(['student_id'=>$item->student_id,'class_student_id'=>$classstudent->id])->orderBy('class_lesson_id DESC')->one();
                  $total = $checkCount+$modelRelaction->lesson;
                  if($lessonCount < $total){ //如果课次表课次数小于词学生转化的课次数
                      $Surplus = $total-$lessonCount;
                      $maxLesson = ClassLesson::find()->where(['class_id'=>$classmanage->class_id])->orderBy('lesson DESC')->one();
                      $sexLesson = ClassLesson::find()->where(['class_id'=>$classmanage->class_id])->orderBy('lesson_id ASC')->limit($artModel->class_count)->asArray()->all();

                      $divide = $Surplus/$artModel->class_count;

                      $i = 1;
                      $x = 1;
                      $insertLesson = [];
                      for($z=0;$z<$divide;$z++){
                          $j = 0;
                          while($j < $artModel->class_count){
                              $time = $maxLesson->class_date+86400*$i;
                              $class_today = date('w',$time);
                              if ($class_today == 0) {
                                  $class_today = 7;
                              }
                              if($artModel->class_day == $class_today){
                                  $insertLesson[] = [
                                      'class_id'=>$maxLesson->class_id,
                                      'class_date'=>$time,
                                      'start_time'=>$maxLesson->start_time,
                                      'end_time'=>$maxLesson->end_time,
                                      'lesson'=>$maxLesson->lesson+$x,
                                      'title' =>$sexLesson[$j]['title'],
                                      'status'=>0,
                                      'ovo'   =>0,
                                      'product_id'   =>$sexLesson[$j]['product_id'],
                                      'lesson_type'   =>$model->order_type,
                                  ];
                                  $x++;
                                  $j++;
                              }

                              $i++;
                          }
                      }

                      Fun::getSiteDb()->createCommand()->batchInsert('{{%class_lesson}}', ['class_id','class_date','start_time', 'end_time','lesson','title','status','ovo','product_id','lesson_type'], $insertLesson)->execute();
                  }
              }
              //修改班级结课时间
              $maxLesson = ClassLesson::find()->where(['class_id'=>$classmanage->class_id])->orderBy('lesson DESC')->one();
              $end_time = Util::getTime($maxLesson->end_time);
              $end = explode(':', $end_time);
              $end_date = date('Y-m-d',$maxLesson->class_date);
              $endTime = strtotime($end_date)+(int)$end[0] * 60 * 60 + (int)$end[1] * 60;
              $classmanage->end_time = $endTime;
              $classmanage->save(false);

              //插入打卡表
              $insertLessonList = ClassLesson::find()->where(['class_id'=>$classmanage->class_id])->andWhere(['>','lesson_id',$MaxCheck->class_lesson_id])->orderBy('lesson_id DESC')->limit($modelRelaction->lesson)->all();
              $insertCheck = [];
              foreach ($insertLessonList as $lesson){
                  $insertCheck[] = [
                      'class_student_id' => $MaxCheck->class_student_id,
                      'order_sales_id' => $item->id,
                      'student_id' => $item->student_id,
                      'status' => 0,
                      'class_lesson_id' => $lesson->lesson_id,
                      'lesson_type' => $model->order_type,
                  ];
              }
              Fun::getSiteDb()->createCommand()->batchInsert('{{%student_check}}', ['class_student_id','order_sales_id','student_id', 'status','class_lesson_id','lesson_type'], $insertCheck)->execute();
             //修改class_student表学生的结课时间
              $maxStudentCheck = StudentCheck::find()->where(['class_student_id'=>$MaxCheck->class_student_id,'student_id'=>$item->student_id])->orderBy('class_lesson_id DESC')->one();
              $studentClassLesson = ClassLesson::findOne($maxStudentCheck->class_lesson_id);
              $end_time = Util::getTime($studentClassLesson->end_time);
              $end = explode(':', $end_time);
              $end_date = date('Y-m-d',$maxLesson->class_date);
              $endTime = strtotime($end_date)+(int)$end[0] * 60 * 60 + (int)$end[1] * 60;
              $classStudentModel = ClassStudent::findOne($MaxCheck->class_student_id);
              $classStudentModel->end_time = $endTime;
              $classStudentModel->save(false);

          }
      }

      public static function AddCheckCount($check_id){
          $Check = StudentCheck::findOne($check_id);
          $ClassLesson = ClassLesson::findOne($Check->class_lesson_id);
          $OrderItemModel = OrdersItems::findOne($Check->order_sales_id);
          $ItemrelationModel = OrdersItemsRelation::find()->where(['orders_items_id'=>$Check->order_sales_id])->one();
          $subCheckModel = SubstituteCheck::find()->where(['student_check_id'=>$check_id])->one();
          $ClassTeacherModel = ClassManageTeacher::find()->where(['class_id'=>$ClassLesson->class_id])->one();
          $StudentModel = Student::findOne($Check->student_id);
          $classstudent = ClassStudent::findOne($Check->class_student_id);
          $check_type = 0;
          $check_user = $Check->student_id;
          if($subCheckModel != null){
              $check_type = 1;
              $check_user = $subCheckModel->userid;
          }
          $class_type = 'appointment';
          $is_scholarship = isset($ItemrelationModel->is_scholarship)?$ItemrelationModel->is_scholarship:1;
          if($is_scholarship == 2 ){
              $class_type = 'consume';
          }
          $is_frequency = isset($classstudent->is_frequency)?$classstudent->is_frequency:0;
//          print_r($classstudent);die;
          if($OrderItemModel->amount > 0  && $classstudent != null) {
              if ($is_frequency == 1) {
                  $price = round($ItemrelationModel->lesson_price / $ItemrelationModel->lesson, 2);
                  $settlement_price = 0;
                  if ($class_type == 'consume') {
                      if($ItemrelationModel->distribution_way > 0)
                          $settlement_price = round($price - ($price * $ItemrelationModel->distribution_proportion / 100), 2);
                  } else {
                      if($ItemrelationModel->subsidy_money > 0)
                          $settlement_price = round($ItemrelationModel->subsidy_money / $ItemrelationModel->lesson, 2);
                  }
              }else{
                  $lastTime = time();
                  $date = date('Y-m-01', $ClassLesson->class_date);
                  $startDay = strtotime(date('Y-m-01', $ClassLesson->class_date));
                  $jiesuanStartDay = strtotime(date('Y-m-21', $ClassLesson->class_date));
                  $jiesuanEndDay = strtotime(date('Y-m-22', $ClassLesson->class_date));
                  $lastday = date('Y-m-d', strtotime("$date +1 month"));
                  if($ClassLesson->class_date >= $jiesuanStartDay && $ClassLesson->class_date < $lastday){ //21-月底时间
                      $newjiesuanStartDay = strtotime(date('Y-m-21', $ClassLesson->class_date));
                      $newjiesuanEndDay = date('Y-m-22', strtotime("$date +1 month"));
                  }
                  if($ClassLesson->class_date >= $startDay && $ClassLesson->class_date < $jiesuanEndDay){  //1-21号上课
                      $newjiesuanStartDay = strtotime(date('Y-m-21', strtotime("$date -1 month")));
                      $newjiesuanEndDay = strtotime(date('Y-m-22', $ClassLesson->class_date));
                  }
                  $price = 0;
                  $settlement_price = 0;
                  $frequencyModel = CheckCount::find()->where(['student_id' => $Check->student_id, 'is_frequency' => 0,'mechanic_id'=>$OrderItemModel->mechanic_id])->andWhere(['between', 'class_time', $newjiesuanStartDay, $newjiesuanEndDay])->one();
                  if($frequencyModel == null ){
                      if ($ItemrelationModel->deadline_type == 'month') {
                          if($ItemrelationModel->lesson_price> 0 && $ItemrelationModel->distribution_proportion > 0) {
                              $moneymonth = ($ItemrelationModel->lesson_price / $ItemrelationModel->deadline) * ($ItemrelationModel->distribution_proportion / 100);
                              $moneymonths = round(($ItemrelationModel->lesson_price / $ItemrelationModel->deadline) - $moneymonth, 2);
                          }
                      } else {
                          if($ItemrelationModel->lesson_price> 0 && $ItemrelationModel->distribution_proportion > 0) {
                              $moneymonth = ($ItemrelationModel->lesson_price / ($ItemrelationModel->deadline * 12)) * ($ItemrelationModel->distribution_proportion / 100);
                              $moneymonths = round(($ItemrelationModel->lesson_price / ($ItemrelationModel->deadline * 12)) - $moneymonth, 2);
                          }
                      }
                      $settlement_price = $moneymonths;
                  }
              }
              $newModel = new CheckCount();
              $newModel->mechanic_id = isset($OrderItemModel->mechanic_id) ? $OrderItemModel->mechanic_id : 0;
              $newModel->goods_id = isset($OrderItemModel->goods_id) ? $OrderItemModel->goods_id : 0;
              $newModel->orders_item_id = isset($OrderItemModel->id) ? $OrderItemModel->id : 0;
              $newModel->orders_items_relation_id = isset($ItemrelationModel->id) ? $ItemrelationModel->id : 0;
              $newModel->teacher_id = isset($ClassTeacherModel->teacher_id) ? $ClassTeacherModel->teacher_id : 0;
              $newModel->customer_id = isset($StudentModel->customer_id) ? $StudentModel->customer_id : 0;
              $newModel->student_id = $Check->student_id;
              $newModel->class_id = $ClassLesson->class_id;
              $newModel->class_lesson_id = $Check->class_lesson_id;
              $newModel->check_id = $Check->id;
              $newModel->lesson = $ClassLesson->lesson;
              $newModel->class_time = $ClassLesson->class_date;
              $newModel->price = $price;
              $newModel->settlement_price = $settlement_price;
              $newModel->status = 0;
              $newModel->check_type = $check_type;
              $newModel->check_user = $check_user;
              $newModel->class_type = $class_type;
              $newModel->is_frequency = $is_frequency;
              $newModel->save(false);
          }
      }
}